package org.opens.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * http请求实现
 *
 * @author by zhangyuming
 * @date 2022/10/25
 */
public class HttpUtil {

    private static final Integer DEFAULT_REQUEST_TIME_OUT = 5000;

    private static final String DEFAULT_RESPONSE_CHARSET = "utf-8";

    /**
     * 功能: 请求接口.
     * <pre>
     * 可以请求下1种controller:
     * - doRequestBody(@RequestBody RequestBodyParam requestBodyParam)
     * </pre>
     * @param url 请求路径
     * @param param 请求参数
     * @return 请求返回值
     */
    public static JSONObject postOfRequestBody(String url, Map<String, Object> param) {
        //Method method = Method.valueOf(type);

        // 创建请求对象
        HttpRequest httpRequest = cn.hutool.http.HttpUtil.createRequest(Method.POST, url)
                .body(new JSONObject(param).toJSONString(0));

        // 执行请求
        HttpResponse httpResponse = httpRequest.timeout(DEFAULT_REQUEST_TIME_OUT)
                .execute();

        // 获取返回值
        String result = httpResponse.charset(DEFAULT_RESPONSE_CHARSET)
                .body();

        // 关闭请求体
        httpResponse.close();

        return new JSONObject(result);
    }

    /**
     * 功能: 请求接口.
     * <pre>
     * 可以请求下两种controller:
     * - doRequestParam(@RequestParam(value = "id") String id)
     * - doRequestObj(ObjParam objParam)
     * 这两种其实都是一样的表单提交类型参数
     * </pre>
     * @param url 请求路径
     * @param param 请求参数
     * @return 请求返回值
     */
    public static JSONObject postOfRequestParam(String url, Map<String, Object> param) {
        //Method method = Method.valueOf(type);

        // 创建请求对象
        HttpRequest httpRequest = cn.hutool.http.HttpUtil.createRequest(Method.POST, url)
                .form(param);

        // 执行请求
        HttpResponse httpResponse = httpRequest.timeout(DEFAULT_REQUEST_TIME_OUT)
                .execute();

        // 获取返回值
        String result = httpResponse.charset(DEFAULT_RESPONSE_CHARSET)
                .body();

        // 关闭请求体
        httpResponse.close();

        return new JSONObject(result);
    }

    public static void main(String[] args) {
        Map<String, Object> p1 = new HashMap<>();
        p1.put("id", 1);

        System.out.println(postOfRequestBody("http://localhost:30000/simpleApi/doRequestBody", p1));
        System.out.println(postOfRequestParam("http://localhost:30000/simpleApi/doRequestObj", p1));
        System.out.println(postOfRequestParam("http://localhost:30000/simpleApi/doRequestParam", p1));
    }

}
